#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFSIZE 1024

char buf[BUFSIZE];

int main(int argc, char *argv[])
{
	if(argc < 3){
		fprintf(stderr, "Usage: del_line <file_path> <line>\n");
                exit(1);
	}
	int line = atoi(argv[2]);
	char* filepath = argv[1];

	int fd1, fd2;

	if((fd1 = open(filepath, O_RDONLY)) < 0){
		perror("fd1: open");
		exit(1);
	}

	if((fd2 = open(filepath, O_WRONLY)) < 0){
		perror("fd2: open");
                exit(1);
	}

	char c;
 	int i = line - 1;
	if(i < 0){
		perror("line should not lower than or equal 0");
                exit(1);
	}
	while(i > 0){
		if((read(fd1, &c, sizeof(c))) != sizeof(c)){
			perror("read");
                	exit(1);
		}
		if(c == '\n'){
			i--;
		}
	}

	off_t pos1 = lseek(fd1, 0, SEEK_CUR);
	while(1){
		if((read(fd1, &c, sizeof(c))) != sizeof(c)){
                        perror("read");
                        exit(1);
                }
		if(c == '\n'){
                        break;
                }
	}
	off_t pos2 = lseek(fd1, 0, SEEK_CUR);

	lseek(fd2, pos1, SEEK_SET);
	int n;
	while((n = read(fd1, &buf, BUFSIZE)) > 0){
		if(write(fd2, &buf, n) != n){
			perror("write");
                        exit(1);
		}
	}
	off_t filesize = lseek(fd1, 0, SEEK_END);

	ftruncate(fd2, filesize - (pos2 - pos1));
	exit(0);
}
